package serv.midser.fileserver;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet Filter implementation class VirtualFileFilter
 */
public class VirtualFileFilter implements Filter {
	
	private String virtualfileMap = "/storage/";
	
	private String resServer = "";

    /**
     * Default constructor. 
     */
    public VirtualFileFilter() {
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
		// TODO Auto-generated method stub
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) res;
		//
		String baseUrl = request.getRequestURI();
		baseUrl = baseUrl.replaceAll("/{1,}", "/");
		if (baseUrl.startsWith(request.getContextPath())) {
			baseUrl = baseUrl.substring(request.getContextPath().length(), baseUrl.length());
		}
		String requestRelativelyUrl = baseUrl;
		if (!virtualfileMap.startsWith("/")) {
			virtualfileMap = "/" + virtualfileMap;
		}
		if (!requestRelativelyUrl.startsWith(virtualfileMap)) {
			chain.doFilter(request, response);
			return;
		}
		StringBuffer buf = new StringBuffer();
		buf.append(resServer + requestRelativelyUrl);
		for (Object key : request.getParameterMap().keySet()) {
			if (buf.indexOf("?") == -1) {
				buf.append("?");
			} else {
				buf.append("&");
			}
			buf.append((String) key);
			buf.append("=");
			buf.append(request.getParameter((String) key));
		}
		((HttpServletResponse) response).sendRedirect(buf.toString());
		return;
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
	}

	public String getVirtualfileMap() {
		return virtualfileMap;
	}

	public void setVirtualfileMap(String virtualfileMap) {
		this.virtualfileMap = virtualfileMap;
	}

	public String getResServer() {
		return resServer;
	}

	public void setResServer(String resServer) {
		this.resServer = resServer;
	}

}
